package b.设计题;

import java.util.ArrayDeque;
import java.util.Deque;

public class 计时器 {

    public int calculate(String s) {
        char[] chars = s.toCharArray();
        int n = chars.length;
        //将所有的空格去掉
        s=s.replaceAll(" ", "");
        //双栈
        Deque<Integer> nums = new ArrayDeque<>();
        Deque<Character> ops = new ArrayDeque<>();
        //
        for (int i = 0; i < n; i++) {
            char cur = chars[i];
            if (cur == '(') {
                ops.addLast(cur);
            } else if (cur == ')') {
                // 计算到最近一个左括号为止
                while (!ops.isEmpty()) {
                    char op = ops.peekLast();
                    if (op != '(') {
                        calc(nums, ops);
                    } else {
                        ops.pollLast();
                        break;
                    }
                }
            } else {
                if (isNum(cur)) {
                    int u = 0;
                    int j = i;
                    // 将从 i 位置开始后面的连续数字整体取出，加入 nums
                    while (j < n && isNum(chars[j]))u=u*10+(int)(chars[j++]-'0');
                    nums.addLast(u);
                    i = j - 1;
                } else {
                    // 有一个新操作要入栈时，先把栈内可以算的都算了
                    if (i > 0 && (chars[i - 1] == '(' || chars[i - 1] == '+' || chars[i - 1] == '-')) {
                        nums.addLast(0);
                    }
                    while (!ops.isEmpty() && ops.peekLast() != '(') calc(nums, ops);
                    ops.addLast(cur);
                }
            }
        }
        //
        while (!ops.isEmpty()) calc(nums, ops);
        return nums.peekLast();
    }
    //
    void calc(Deque<Integer> nums, Deque<Character> ops) {
        int b = nums.pollLast(), a = nums.pollLast();
        char op = ops.pollLast();
        if(op=='+')nums.addLast(a+b);
        else if(op=='-')nums.addLast(a-b);
    }
    //
    boolean isNum(char c) {
        return Character.isDigit(c);
    }
}
